// 为小程序环境提供 Base64 编码/解码的 polyfill
function btoaPolyfill(str: string): string {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
  let output = ''
  const bytes = new Uint8Array(str.length)
  for (let i = 0; i < str.length; i++) {
    bytes[i] = str.charCodeAt(i)
  }

  for (let i = 0; i < bytes.length; i += 3) {
    const byteNum = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]
    const chunk = [
      chars[(byteNum >> 18) & 0x3F],
      chars[(byteNum >> 12) & 0x3F],
      chars[(byteNum >> 6) & 0x3F],
      chars[byteNum & 0x3F],
    ]
    output += chunk.join('')
  }

  return output
}

function atobPolyfill(str: string): string {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
  let output = ''
  str = String(str).replace(/=+$/, '')

  if (str.length % 4 === 1) {
    throw new Error('Invalid base64 string')
  }

  let bc = 0
  let bs = 0
  for (let i = 0; i < str.length; i++) {
    const buffer = str.charAt(i)
    const index = chars.indexOf(buffer)
    if (index !== -1) {
      bs = bc % 4 ? bs * 64 + index : index
      if (bc++ % 4) {
        output += String.fromCharCode(255 & (bs >> (-2 * bc & 6)))
      }
    }
  }

  return output
}

// 使用原生函数或 polyfill
const btoa = typeof globalThis.btoa !== 'undefined' ? globalThis.btoa : btoaPolyfill
const atob = typeof globalThis.atob !== 'undefined' ? globalThis.atob : atobPolyfill

// 加密数据
export function encryptData(data: any): string {
  try {
    const jsonStr = JSON.stringify(data)
    // 使用 Base64 编码替代 MD5 哈希
    return btoa(unescape(encodeURIComponent(jsonStr)))
  }
  catch (error) {
    console.error('Encryption failed:', error)
    return ''
  }
}

// 解密数据
export function decryptData(encrypted: string): any {
  if (!encrypted)
    return null
  try {
    // 解码 Base64 并解析 JSON
    const jsonStr = decodeURIComponent(escape(atob(encrypted)))
    return JSON.parse(jsonStr)
  }
  catch (error) {
    console.error('Decryption failed:', error)
    return null
  }
}

// 加密存储
export function encryptStorage(key: string, value: any) {
  try {
    const encrypted = encryptData(value)
    uni.setStorageSync(key, encrypted)
  }
  catch (error) {
    console.error('Storage encryption failed:', error)
  }
}

// 解密存储
export function decryptStorage(key: string) {
  try {
    const encrypted = uni.getStorageSync(key)
    if (!encrypted)
      return null
    return decryptData(encrypted)
  }
  catch (error) {
    console.error('Storage decryption failed:', error)
    // 如果解密失败，清除损坏的数据
    try {
      uni.removeStorageSync(key)
      console.log(`Cleared corrupted storage data for key: ${key}`)
    }
    catch (clearError) {
      console.error('Failed to clear corrupted storage:', clearError)
    }
    return null
  }
}

// 清理所有损坏的存储数据
export function clearCorruptedStorage() {
  try {
    const keys = ['ECHO-STORE']
    keys.forEach((key) => {
      try {
        const data = uni.getStorageSync(key)
        if (data) {
          // 尝试解密，如果失败则清除
          const decrypted = decryptData(data)
          if (decrypted === null) {
            uni.removeStorageSync(key)
            console.log(`Cleared corrupted storage data for key: ${key}`)
          }
        }
      }
      catch (error) {
        console.error(`Error checking storage key ${key}:`, error)
        try {
          uni.removeStorageSync(key)
          console.log(`Cleared storage data for key: ${key}`)
        }
        catch (clearError) {
          console.error(`Failed to clear storage key ${key}:`, clearError)
        }
      }
    })
  }
  catch (error) {
    console.error('Failed to clear corrupted storage:', error)
  }
}
